package nbn.android.myyoutubeclient;

import java.util.ArrayList;

import nbn.android.myyoutubeclient.object.UserObject;
import nbn.android.myyoutubeclient.object.VideoObject;
import nbn.android.myyoutubeclient.parse.Parser;
import nbn.android.myyoutubeclient.parse.ParserUser;
import nbn.android.myyoutubeclient.util.BaseEngine;
import nbn.android.myyoutubeclient.util.CMD;
import nbn.android.myyoutubeclient.util.TagName;
import nbn.android.myyoutubeclient.videocontrol.FullScreenVideoStreamView;
import nbn.android.myyoutubeclient.videocontrol.VideoControllerStreamView;
import nbn.android.myyoutubeclient.view.BounceProgressBar;

import org.w3c.dom.NodeList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.youtube.player.YouTubePlayer;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;

@SuppressLint("InlinedApi")
public class VideoPlayActivity extends Activity implements FullScreenVideoStreamView.ToggleFullScreen {
	String tag = VideoPlayActivity.class.getName();
	public String YOUTUBE = "1";
	public String LINK = "2";
	private FullScreenVideoStreamView mVideoView;
	private ProgressBar bar,authorBar;
	BounceProgressBar detailBar;
	int height;
	int width;
	RelativeLayout relativeLayout;
	public VideoObject songObject;
	public ArrayList<VideoObject> listSongs;
	boolean isOnline = false;
	int index = -1;
	boolean isshow = false;
	TextView VideoTitle, VideoViewed, VideoLike, VideoDislike, VideoAuthor, VideoDescription;
	ImageView ImageAuthor;

	YouTubePlayer player;
	@SuppressWarnings("unchecked")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		if (Build.VERSION.SDK_INT < 16) {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		} else {
			View decorView = getWindow().getDecorView();
			int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
			decorView.setSystemUiVisibility(uiOptions);
		}
		setContentView(R.layout.video_stream);
		findviewbyid();
		Bundle extras = getIntent().getExtras();
		if (getIntent().hasExtra(TagName.INDEX))
			index = extras.getInt(TagName.INDEX);
		if (index >= 0) {
			listSongs = (ArrayList<VideoObject>) extras.getSerializable(TagName.KEY);
			songObject = listSongs.get(index);
		} else {
			songObject = (VideoObject) extras.getSerializable(TagName.KEY);
		}
//		songObject.showinfo();
//		player.set
		playVideo();
		showVideoinfo(songObject);
	}

	void findviewbyid() {
		relativeLayout = (RelativeLayout) findViewById(R.id.video_realati_videoview);
		bar = (ProgressBar) findViewById(R.id.videoplayerPreloader);
		mVideoView = (FullScreenVideoStreamView) findViewById(R.id.video_view);
		VideoAuthor = (TextView) findViewById(R.id.textView_author);
		VideoTitle = (TextView) findViewById(R.id.textView_Videotitle);
		VideoViewed = (TextView) findViewById(R.id.textView_Viewed);
		VideoLike = (TextView) findViewById(R.id.textView_like);
		VideoDislike = (TextView) findViewById(R.id.textView_dislike);
		VideoDescription = (TextView) findViewById(R.id.textView_description);
		ImageAuthor = (ImageView) findViewById(R.id.image_author);
		detailBar=(BounceProgressBar) findViewById(R.id.progressBar_videoinfo);
		authorBar=(ProgressBar) findViewById(R.id.progressBar_Imageauthor);
	}

	void showVideoinfo(VideoObject videoobj) {
		VideoTitle.setText(videoobj.gettitle());
		mVideoView.mMediaController.setTitle(songObject.gettitle());
		VideoViewed.setText(BaseEngine.numbershowdetails(videoobj.getview()) + " views");
		VideoLike.setText(BaseEngine.numbershowdetails(videoobj.getlike()));
		VideoDislike.setText(BaseEngine.numbershowdetails(videoobj.getdislike()));
		VideoDescription.setText(videoobj.getdescription());
//		new LoadMoviesAsync().execute("");
	}

	private void playVideo() {
		String url =songObject.getVideo_id();
		mVideoView.setOnToggleFullScreen(this);
		mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {
				bar.setVisibility(View.GONE);
			}
		});

		calculateVideoViewSize();
		mVideoView.setMediaController(new VideoControllerStreamView(this));
		mVideoView.setDimensions(width, height);
		String lYouTubeFmtQuality = "18";
//		WifiManager lWifiManager = (WifiManager) VideoPlayActivity.this.getSystemService(Context.WIFI_SERVICE);
//		TelephonyManager lTelephonyManager = (TelephonyManager) VideoPlayActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
//		if ((lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0)
//				|| ((lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS 
//						|| lTelephonyManager.getNetworkType() == 5 /* EVDO_0 */
//						|| lTelephonyManager.getNetworkType() == 6 /**/ 
//						|| lTelephonyManager.getNetworkType() == 8 /* HSDPA */
//						|| lTelephonyManager.getNetworkType() == 9 /* HSUPA - 5.76 Mbit/s */
//						|| lTelephonyManager.getNetworkType() == 10 /* HSPA */)
//						&& lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)) 
//		{
//			lYouTubeFmtQuality = "18";
//		}
		mVideoView.setYoutubeId(lYouTubeFmtQuality, url);
		mVideoView.requestFocus();
		mVideoView.start();
	}

	public String checkVideoPath(String path) {
		return path.replaceAll(" ", "%20");
	}

	@Override
	protected void onPause() {
		super.onPause();
		mVideoView.suspend();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mVideoView.resume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.songObject = null;
		if (listSongs != null) {
			this.listSongs.clear();
			this.listSongs = null;
		}

	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		calculateVideoViewSize();
		// Checks the orientation of the screen
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
			mVideoView.setFullScreen(true);
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			mVideoView.setFullScreen(false);
		}
		mVideoView.setDimensions(width, height);
		mVideoView.getHolder().setFixedSize(width, height);
		bar.refreshDrawableState();
	}

	private void calculateVideoViewSize() {
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		if (metrics.widthPixels < metrics.heightPixels) {
			height = (int) (metrics.widthPixels / 1.55);
			width = metrics.widthPixels;
		} else {
			width = metrics.widthPixels;
			height = metrics.heightPixels;
		}
		LinearLayout.LayoutParams layoutParams = (android.widget.LinearLayout.LayoutParams) relativeLayout.getLayoutParams();
		layoutParams.height = height;
		relativeLayout.setLayoutParams(layoutParams);
		relativeLayout.requestLayout();
	}

	@Override
	public void onToggleFullScreen(boolean isFullScreen) {
		setRequestedOrientation(isFullScreen ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	class LoadMoviesAsync extends AsyncTask<String, UserObject, UserObject> {
		@Override
		protected UserObject doInBackground(String... params) {
			UserObject result=null;
			String url = String.format(CMD.GDATA_USER_DETAILS, songObject.getuploaderId());
			Log.e(tag, "url: " + url);
			Parser parser = new Parser();
			NodeList movieContentLst = parser.getResponceNodeList(url);
			if (movieContentLst != null) {
//				for (int i = 0; i < movieContentLst.getLength(); i++) {
				result=	ParserUser.getResult(movieContentLst);
//				}
			}
			return result;
		}
		@Override
		protected void onPostExecute(UserObject result) {
			if(result!=null){
				Picasso.with(VideoPlayActivity.this).load(result.getthumbnail()).into(ImageAuthor, new Callback() {
					@Override
					public void onSuccess() {
						authorBar.setVisibility(View.GONE);
					}
	
					@Override
					public void onError() {
						authorBar.setVisibility(View.GONE);
					}
				});
				VideoAuthor.setText(result.gettitle());
			}
			detailBar.setVisibility(View.GONE);
			
			super.onPostExecute(result);
		}
		
	}
}
